package com.zwcl.common.core.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description restTemplate参数构建util
 * @Author tanljs
 * @Date 2019/8/22
 * @Email Alex.tan@wetax.com.cn
 */
public final class RestUtils {

    /**
     * 普通Map构建HttpEntity
     * @param maps
     * @return
     */
    public static HttpEntity<MultiValueMap<String, Object>> mapParamsAndheader(Map maps) {
        HttpHeaders headers = new HttpHeaders();
        // 窗体数据被编码为名称/值对
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        //判断maps 是否为空
        if (maps != null) {
            if (!maps.isEmpty()) {
                maps.forEach((k, v) -> buildMap(map, k.toString(), v));
            }
        }
        return new HttpEntity<>(map, headers);
    }

    /**
     * 通过Map 来创建参数
     */
    private static void buildMap(MultiValueMap<String, Object> map, String key, Object value) {
        if (value == null) {
            return;
        }
        if (value.getClass().isArray()) {
            if (((Object[]) value).length == 0) {
                return;
            }
            map.put(key, Arrays.asList((Object[]) value).stream().map(Object::toString).collect(Collectors.toList()));
        } else if (value instanceof List) {
            if (((List<Object>) value).isEmpty()) {
                return;
            }
            map.put(key, ((List<Object>) value).stream().map(Object::toString).collect(Collectors.toList()));
        } else if (value instanceof Map) {
            ((Map<?, ?>) value).forEach((k, v) -> buildMap(map, key + "." + k, v));
        } else {
            map.add(key, value.toString());
        }
    }
}
